/**
 * Project Name:ResultUtils.java
 * File Name:ResultUtils.java
 * Date:2019/3/10 17:53
 * Copyright (c) 2019, zhang.xiangyu@foxmail.com All Rights Reserved.
 */
package com.meatball.utils.response;

import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import static org.springframework.web.reactive.function.BodyInserters.fromObject;
import static org.springframework.web.reactive.function.server.ServerResponse.ok;

/**
 * @Title: ResultUtils.java
 * @Description: todo(消息返回)
 * @Author: 張翔宇
 * @Date: 2019/3/10 17:54
 * @Version: V1.0
 */
public class ResultUtils {

    /**
     * @title: response
     * @description: todo(返回分页数据)
     * @params: [data]
     * @return: reactor.core.publisher.Mono<org.springframework.web.reactive.function.server.ServerResponse>    返回类型
     * @author: 張翔宇
     * @date: 2019/4/10 10:42
     */
    public static <T> Mono<ServerResponse> response (Mono<T> data) {
        return data.flatMap(item -> ok().contentType(MediaType.APPLICATION_JSON)
                .body(fromObject(item)))
                .switchIfEmpty(ServerResponse.notFound().build());
    }

    /**
     * @title: response
     * @description: todo(传入一个Mono参数)
     * @params: [code, message, data]
     * @return: reactor.core.publisher.Mono<org.springframework.web.reactive.function.server.ServerResponse>    返回类型
     * @author: 張翔宇
     * @date: 2019/3/10 17:54
     */
    public static <T> Mono<ServerResponse> response (int code, String message, Mono<T> data) {
        return data.flatMap(item -> ok().contentType(MediaType.APPLICATION_JSON)
                .body(fromObject(new ResultMsg(code, message, item))))
                .switchIfEmpty(ServerResponse.notFound().build());
    }

    /**
     * @title: response
     * @description: todo(传入一个Flux参数)
     * @params: [code, message, data]
     * @return: reactor.core.publisher.Mono<org.springframework.web.reactive.function.server.ServerResponse>    返回类型
     * @author: 張翔宇
     * @date: 2019/3/10 17:54
     */
    public static <T> Mono<ServerResponse> response (int code, String message, Flux<T> data) {
        return data.collectList().flatMap(item -> ok().contentType(MediaType.APPLICATION_JSON)
                .body(fromObject(new ResultMsg(code, message, item.size() > 1 ? item : item.get(0)))))
                .switchIfEmpty(ServerResponse.notFound().build());
    }

    /**
     * @title: response
     * @description: todo(无参数)
     * @params: [code, message]
     * @return: reactor.core.publisher.Mono<org.springframework.web.reactive.function.server.ServerResponse>    返回类型
     * @author: 張翔宇
     * @date: 2019/3/10 17:54
     */
    public static Mono<ServerResponse> response (int code, String message) {
        return ok().contentType(MediaType.APPLICATION_JSON).body(fromObject(new ResultMsg(code, message)));
    }
}
